package com.woyowodaows.activity.mine;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.woyowodaows.R;
import com.woyowodaows.base.BaseActivity;
import com.woyowodaows.base.ImageDataBean;
import com.woyowodaows.bean.home.UserDataBean;
import com.woyowodaows.bean.mine.UserInfoBean;
import com.woyowodaows.dialog.MyProgressDialog;
import com.woyowodaows.dialog.SingleListDialog;
import com.woyowodaows.popupwind.ChoosePicWindow;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.CacheUserInfoUtils;
import com.woyowodaows.utils.GlideImageLoader;
import com.woyowodaows.utils.ImageLoaderUtlis;
import com.woyowodaows.utils.RegularUtils;
import com.woyowodaows.utils.ToastUtil;
import com.woyowodaows.weight.PersonItemView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2019/4/1.
 * 个人中心详情
 */

public class PersonalCenteActivity extends BaseActivity {
    @BindView(R.id.piv_person_nike_name)
    PersonItemView pivPersonNikeName;
    @BindView(R.id.piv_person_phoen)
    PersonItemView pivPersonPhoen;
    @BindView(R.id.piv_person_address)
    PersonItemView pivPersonAddress;
    @BindView(R.id.piv_person_real_name)
    PersonItemView pivPersonRealName;
    @BindView(R.id.piv_person_sex)
    PersonItemView pivPersonSex;
    @BindView(R.id.piv_person_email)
    PersonItemView pivPersonEmail;
    @BindView(R.id.iv_person_info_head)
    ImageView ivPersonInfoHead;
    private UserInfoBean userInfoBean;
    private String choose = "";
    private MyProgressDialog dialog;

    private String updownUrl;
    //相册-相册
    String[] photo = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private ChoosePicWindow popupwindow;
    private static final int REQUEST_CAMERA_CODE = 100;

    private ArrayList<ImageItem> imageItems;
    private File filesImg;

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_cente;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //用户性别  1男 2女 0未知
                    if (pivPersonSex.getHint().equals("男")) {
                        userInfoBean.setGender("1");
                    } else if (pivPersonSex.getHint().equals("女")) {
                        userInfoBean.setGender("2");
                    } else if (pivPersonSex.getHint().equals("未知")) {
                        userInfoBean.setGender("0");
                    }
                    CacheUserInfoUtils.setUserInfo(userInfoBean);
                    break;
                case 6:
                    CacheUserInfoUtils.setUserInfo(userInfoBean);
                    break;
                case 1:
                    ToastUtil.show_short(mContext, "修改失败");
                    break;
                case 2:
                    ToastUtil.show_short(mContext, "无权限");
                    break;
                case 3:
                    uploadMultipleImages(filesImg, null);
                    break;

            }
        }
    };


    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this);
        setTitleBar(false, "个人信息", "", 0, 0, null);
        if (CacheUserInfoUtils.getUserInfo() != null) {
            userInfoBean = CacheUserInfoUtils.getUserInfo(); //0 处理中 1 成功 2失败
        }
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        dialog = new MyProgressDialog(this);
        ImageLoaderUtlis.displayHeadImage(mContext, userInfoBean.getAvatar(), R.mipmap.icon_header, ivPersonInfoHead);
    }

    @Override
    public void initData() {
        super.initData();
        setStyle(pivPersonNikeName, "昵称", 0);
        setStyle(pivPersonRealName, "设置姓名", 0);
        setStyle(pivPersonSex, "性别", 0);
        setStyle(pivPersonPhoen, "手机号码", 0);
        setStyle(pivPersonAddress, "详细地址", 0);
        setStyle(pivPersonEmail, "设置邮箱", 0);
        //昵称
        if (!TextUtils.isEmpty(userInfoBean.getNickname())) {
            pivPersonNikeName.setHint(userInfoBean.getNickname());
        } else {
            pivPersonNikeName.setHint("未设置");
        }
        //姓名
        if (!TextUtils.isEmpty(userInfoBean.getRealname())) {
            pivPersonRealName.setHint(userInfoBean.getRealname());
        } else {
            pivPersonRealName.setHint("未设置");
        }
        // 性别判断
        String sexStr = "";
        if (userInfoBean != null) { //1男 2女 0未未知
            if (Integer.valueOf(userInfoBean.getGender()) == 2) {
                sexStr = "女";
            } else if (Integer.valueOf(userInfoBean.getGender()) == 1) {
                sexStr = "男";
            } else {
                sexStr = "未知";
            }
            pivPersonSex.setHint(sexStr);
        }
        //手机号码
        if (!TextUtils.isEmpty(userInfoBean.getPhone())) {
            pivPersonPhoen.setHint(RegularUtils.getPhone(userInfoBean.getPhone()));
        } else {
            pivPersonPhoen.setHint(RegularUtils.getPhone("未设置"));
        }
        //邮箱
        if (!TextUtils.isEmpty(userInfoBean.getEmail())) {
            pivPersonEmail.setHint(userInfoBean.getEmail());
        } else {
            pivPersonEmail.setHint("未设置");
        }
    }

    @OnClick({
            R.id.piv_person_address,
            R.id.rl_person_info_img,
            R.id.piv_person_sex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.piv_person_address://详细地址
//                Intent intent=new Intent(mContext,DetailedAddressActivity.class);
//                intent.putExtra("regisType","1");
//                startActivity(intent);
                break;
            case R.id.rl_person_info_img:
                choosePhto();
                break;
            case R.id.piv_person_sex://性别
                final String[] items = new String[]{"男", "女"};

                final SingleListDialog dialog = new SingleListDialog(mContext, items);
                dialog.setTitle("修改性别");
                dialog.setOnItemClickListener(new SingleListDialog.OnItemClickListener() {
                    @Override
                    public void ItemClickListener(int i) {
                        choose = items[i];
                        pivPersonSex.setHint(items[i]);
//                1男 2女 0未知
                        if (choose.equals("男")) {
                            editSex("1");
                        } else if (choose.equals("女")) {
                            editSex("2");
                        }

                        dialog.dismiss();
                    }
                });

                dialog.show();
                break;

        }
    }

    private void setStyle(PersonItemView piv, String text, int code) {
        piv.setTextView(text);
        piv.setCode(code);
        piv.setHint("未设置");

    }

    @OnClick({R.id.piv_person_nike_name,
            R.id.piv_person_real_name,
            R.id.piv_person_email
    })
    public void setInfo(PersonItemView view) {
        Intent intent = new Intent(this, PersonManagerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("MARK", view.getTextView());
        bundle.putString("INFORMATION", view.getHint());
        intent.putExtras(bundle);
        startActivityForResult(intent, view.getCode());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem bean = imageItems.get(0);
                if (imageItems != null && imageItems.size() > 0) {
                    if (filesImg == null) {
                        filesImg = new File(bean.path);
                    }
                    filesImg = new File(bean.path);
                    Message.obtain(handler, 3).sendToTarget();
                    //  Log.i("zys",filesImg.toString());
                } else {
                    ToastUtil.show(mContext, "获取照片失败,请重试！");
                }
            }
            switch (resultCode) {
                case 5://昵称
                    if (data != null) {
                        pivPersonNikeName.setHint(data.getStringExtra("nick"));
                        userInfoBean.setNickname(data.getStringExtra("nick"));
                    }
                    break;
                case 2://姓名
                    if (data != null) {
                        String pivRealName = data.getStringExtra("RealName");
                        pivPersonRealName.setHint(pivRealName);
                        userInfoBean.setRealname(pivRealName);
                    }
                    break;

                case 4:
                    if (data != null) {
//                            String pivAddress = data.getStringExtra("pivAddress");
//                            pivDetailedAddress.setHint("已设置");
//                            userInfoBean.setAddr(pivAddress);
                    }
                    break;
                case 8:
                    if (data != null) {
                        String email = data.getStringExtra("rlEmail");
                        pivPersonEmail.setHint(email);
                        userInfoBean.setEmail(email);
                    }
                    break;
            }
            CacheUserInfoUtils.setUserInfo(userInfoBean);
        }
    }


    //编辑sex
    public void editSex(String sexStr) {

        //        fieldName:email   // email 电子邮箱格式       gender:1男 2女       realname 真实姓名必须是中文     birthday 请确认你输入生日是否正确    nickname:昵称不能为空  avatar: 头像路径不能为空
//        fieldValue:332741160@qq.com
        Map<String, Object> mapParameter = new HashMap<>();
        mapParameter.put("fieldName", "gender");
        mapParameter.put("fieldValue", sexStr);//昵称
        HttpAsyncTask.getInstance().onPostParam(mContext, "", false, InterfaceUrl.UPDATEUSERINFO, UserDataBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    UserDataBean bean = (UserDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        if (handler != null) {
                            handler.sendEmptyMessage(0);
                            ToastUtil.show(mContext, bean.getMessage());
                        }
                    } else {
                        ToastUtil.show(mContext, bean.getMessage());
                    }
                }
            }

            @Override
            public void onError(String message) {
                ToastUtil.show(mContext, message);
            }
        });


    }

    /**
     * 上传多张图片
     */
    public void uploadMultipleImages(File files, final ArrayList<ImageItem> imageItems) {
//        File fileImge=new File(videoFirstImagePath);
        showProgressDialog(mContext, "上传中...");
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostFile(mContext, "", false, files, mapParameter, ImageDataBean.class, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    ImageDataBean bean = (ImageDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
//                        updownUrl = bean.getData().getStrFileName();
                        if (bean != null && bean.getData().size() > 0) {
                            updownUrl = bean.getData().get(0).getPath();
                           updataHead();
                        }
                        setImageAdapterData(bean.getData().get(0).getVisitUrl());
                    } else {
                        ToastUtil.show(mContext, bean.getMessage());
                    }
                    dismissProgressDialog();
                }
            }

            @Override
            public void onError(String message) {
                dismissProgressDialog();
                ToastUtil.show(mContext, message);
            }
        });
    }

    public void setImageAdapterData(String url) {//ArrayList<ImageItem> imageItems

        if (imageItems != null && imageItems.size() > 0) {
            GlideImageLoader.displayHeadImage(mContext, url, R.mipmap.icon_header, ivPersonInfoHead);

        }
    }

    private void choosePhto() {
        if (popupwindow == null) {
            popupwindow = new ChoosePicWindow(this, tvTitle, "0");// 0显示一个按钮
        }
        popupwindow.showPopupWindow();
        popupwindow.setOnItemClickListener(new ChoosePicWindow.OnItemClickListener() {
            @Override
            public void onTake() {
                if (EasyPermissions.hasPermissions(mContext, photo)) {//检查是否获取该权限
                    openCamera();
                } else {
                    EasyPermissions.requestPermissions(this, "应用需要获取相机拍照和获取相册权限!", 1, photo);
                }
                popupwindow.hidePopupWindow();
            }

            @Override
            public void onChoose() {
                if (EasyPermissions.hasPermissions(mContext, photo)) {//检查是否获取该权限
                    openPhoto();
                } else {
                    EasyPermissions.requestPermissions(this, "应用需要获取相机拍照和获取相册权限!", 1, photo);
                }
                popupwindow.hidePopupWindow();
            }
        });
    }


    /**
     * 打开相机
     */
    private void openCamera() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setCrop(true);
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        intent.putExtra("CropType", "6");//裁剪状态
        startActivityForResult(intent, REQUEST_CAMERA_CODE);
    }

    /**
     * 打开相册
     */
    private void openPhoto() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setCrop(true);
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra("CropType", "6");//裁剪状态
        startActivityForResult(intent, REQUEST_CAMERA_CODE);

    }

    //编辑sex
    public void updataHead() {

        //        fieldName:email   // email 电子邮箱格式       gender:1男 2女       realname 真实姓名必须是中文     birthday 请确认你输入生日是否正确    nickname:昵称不能为空  avatar: 头像路径不能为空
//        fieldValue:332741160@qq.com
        Map<String, Object> mapParameter = new HashMap<>();
        mapParameter.put("fieldName","avatar");
        mapParameter.put("fieldValue",updownUrl);//头像
        HttpAsyncTask.getInstance().onPostParam(mContext, "", false, InterfaceUrl.UPDATEUSERINFO, UserDataBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    UserDataBean bean = (UserDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        userInfoBean.setAvatar(bean.getFileUrl()+userInfoBean.getAvatar());
                        CacheUserInfoUtils.setUserInfo(userInfoBean);
//                        ImageLoaderUtlis.displayHeadImage(mContext, updownUrl, R.mipmap.icon_header,ivPersonInfoHead);
                        ToastUtil.show_short(mContext, "上传成功！");
                    } else {
                        ToastUtil.show(mContext, bean.getMessage());
                    }
                }
            }

            @Override
            public void onError(String message) {
                ToastUtil.show(mContext, message);
            }
        });


    }


}
